package yzy.ecps.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import yzy.ecps.model.BtcPtlUser;
import yzy.ecps.model.BtcShipAddr;
import yzy.ecps.service.PtlUserService;
import yzy.ecps.service.ShipAddrService;
import yzy.ecps.utils.EcpsUtils;
import yzy.ecps.utils.MD5;

@Controller
@RequestMapping("/user")
public class PersonController {
	
	@Autowired
	private PtlUserService userService;
	@Autowired
	private ShipAddrService addrService;
	
	/**
	 * 页面加载时从session中获取前台用户信息响应给浏览器
	 * @param session
	 * @param response
	 */
	@RequestMapping("/getUser.do")

	public void getUser(HttpSession session,HttpServletResponse response){
		BtcPtlUser user = (BtcPtlUser) session.getAttribute("user");
		JSONObject json = new JSONObject();
		json.accumulate("user", user);
		String result = json.toString();
		EcpsUtils.printResultForUTF8(result, response);
	}
	
	/**
	 * 登陆页面
	 * @return
	 */
	@RequestMapping("/loginPage.do")
	public String loginPage(){
		return "passport/login";
	}
	
	/**
	 * 个人中心页面
	 * @return
	 */
	@RequestMapping("/checkuser/index.do")
	public String index(){
		return "/person/index";
	}
	
	/**
	 * 登陆
	 * @param username
	 * @param password
	 * @param captcha
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping("/login.do")
	public String login(String username,String password,String captcha,HttpSession session,Model model){
		/*if(!captcha.equalsIgnoreCase(session.getAttribute("piccode").toString())){
			model.addAttribute("tip", "caperror");
			return "passport/login";
		}*/
		password = MD5.GetMD5Code(password);
		BtcPtlUser ptlUser = userService.getLoginUser(username, password);
		if(ptlUser == null){
			model.addAttribute("tip", "userpasserror");
			return "passport/login";
		}
		session.setAttribute("user", ptlUser);
		return "redirect:/item/index.do";
	}
	
	/**
	 * 获取验证码
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/getImage.do")
	public void getImage(HttpServletRequest request,HttpServletResponse response) throws IOException{
		captcha(request,response);
	}
	
	/**
	 * 收货地址管理页面
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping("/checkuser/addrPage.do")
	public String addrPage(HttpSession session,Model model){
		BtcPtlUser user = (BtcPtlUser) session.getAttribute("user");
		List<BtcShipAddr> aList = addrService.findAllAddrForUser(user.getPtlUserId());
		model.addAttribute("user", user);
		model.addAttribute("aList",aList);
		return "/person/deliverAddress";
	}
	
	/**
	 * 添加或修改用户收货地址
	 * @param addr
	 * @return
	 */
	@RequestMapping("/checkuser/saveOrUpdateAddr.do")
	public String saveOrUpdateAddr(BtcShipAddr addr){
		Long userId = addr.getPtlUserId();
		Long addrId = addr.getShipAddrId();
		if(addr.getDefaultAddr() == null)
			addr.setDefaultAddr(0);
		if(addrId == null){
			addrService.addAddrForUser(addr, userId);
		}
		else 
			addrService.updateAddrForUser(userId, addr);
		return "redirect:/user/checkuser/addrPage.do";
	}
	
	
	/**
	 * 查询一个收货地址
	 * @param shipAddrId
	 * @param response
	 */
	@RequestMapping("/checkuser/findAddr.do")
	public void ajax_findAddr(Long shipAddrId,HttpServletResponse response){
		BtcShipAddr addr = addrService.findAddrById(shipAddrId);
		JSONObject json = new JSONObject();
		json.accumulate("addr", addr);
		EcpsUtils.printResultForUTF8(json.toString(), response);
	}
	
	/**
	 * 更改用户的默认收货地址
	 * @param shipAddrId
	 * @param session
	 * @return
	 */
	@RequestMapping("/checkuser/changeDefaultAddr.do")
	public String changeDefaultAddr(Long shipAddrId,HttpSession session){
		BtcPtlUser user = (BtcPtlUser) session.getAttribute("user");
		Long userId = user.getPtlUserId();
		addrService.changeDefaultAddr(shipAddrId, userId);
		return "redirect:/user/checkuser/addrPage.do";
	}
	
	/**
	 * 删除用户收货地址
	 * @param shipAddrId
	 * @return
	 */
	@RequestMapping("/checkuser/deleteAddr.do")
	public String deleteAddr(Long shipAddrId){
		addrService.deleteAddr(shipAddrId);
		return "redirect:/user/checkuser/addrPage.do";
	}
	
	/**
	 * 获取当前用户收货地址的个数
	 * @param ptlUserId
	 * @param out
	 * @throws IOException
	 */
	@RequestMapping("/checkuser/getAddrCount.do")
	public void ajax_getAddrCount(Long ptlUserId,HttpServletResponse out) throws IOException{
		String count = "";
		List<BtcShipAddr> aList = addrService.findAllAddrForUser(ptlUserId);
		count += aList.size();
		out.getWriter().write(count);
	}
	private void captcha(HttpServletRequest request,HttpServletResponse response) throws IOException{
		BufferedImage img = new BufferedImage(68, 22,  
				  
		        BufferedImage.TYPE_INT_RGB);  
		  
		        // 得到该图片的绘图对象    
		  
		        Graphics g = img.getGraphics();  
		  
		        Random r = new Random();  
		  
		        Color c = new Color(200, 150, 255);  
		  
		        g.setColor(c);  
		  
		        // 填充整个图片的颜色    
		  
		        g.fillRect(0, 0, 68, 22);  
		  
		        // 向图片中输出数字和字母    
		  
		        StringBuffer sb = new StringBuffer();  
		  
		        char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();  
		  
		        int index, len = ch.length;  
		  
		        for (int i = 0; i < 4; i++) {  
		  
		            index = r.nextInt(len);  
		  
		            g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt  
		  
		            (255)));  
		  
		            g.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 22));  
		            // 输出的  字体和大小                      
		  
		            g.drawString("" + ch[index], (i * 15) + 3, 18);  
		            //写什么数字，在图片 的什么位置画    
		  
		            sb.append(ch[index]);  
		  
		        }  
		  
		        request.getSession().setAttribute("piccode", sb.toString());  
		  
		        ImageIO.write(img, "JPG", response.getOutputStream());
	}
}
